trigger OORAllignMembersforAssignment on Assignment_Groups__c (before insert, before update) {
 
    List<Assignment_Groups__c> UpdatedList= New List<Assignment_Groups__c>();
    Map<Id,List<Assignment_Groups__c>> grpmap= New Map<Id,List<Assignment_Groups__c>>();
    Set<Id> AssignGrpList = New Set<Id>(); 
    Set<Id> UserIds = new Set<Id>();
    Set<Id> UpdatedIds = new Set<Id>();
    Set<Id> asGrpmemberIds = new Set<Id>();
    Set<Id> ContainedIds = new Set<Id>();
    for(Assignment_Groups__c ag : Trigger.new)
        {
           if(ag.OOR_Assignment_Type__c == 'Lead' || ag.OOR_Assignment_Type__c == 'NMR - Lead'){
           if(Trigger.ISINSERT){
               UserIds.add(ag.User__c);
               AssignGrpList.add(ag.Group_Name__c);
               UpdatedList.add(ag);
           }               
           if(Trigger.ISUPDATE &&((ag.Active__c != Trigger.oldMap.get(ag.id).Active__c && ag.Active__c == 'True') || (ag.User_Active__c == 'True' && ag.User_Active__c != Trigger.oldMap.get(ag.id).User_Active__c))){
               UpdatedList.add(ag);
               UserIds.add(ag.User__c);
               AssignGrpList.add(ag.Group_Name__c);
               UpdatedIds.add(ag.Id);
               //asGrpmemberIds.add();
               }
            else if(Trigger.ISUPDATE && (ag.User__c != Trigger.oldMap.get(ag.id).User__c)){
                 UpdatedList.add(ag);
                 UserIds.add(ag.User__c);
                 AssignGrpList.add(ag.Group_Name__c);
                 UpdatedIds.add(ag.Id);
             }
           }
         } 
         if(UserIds.size()>0 && Trigger.ISINSERT){
            
            for(Assignment_Groups__c agnewlist:[Select Id,User__c from Assignment_Groups__c where User__c IN:UserIds AND Id NOT IN:UpdatedIds]){
                ContainedIds.add(agnewlist.User__c);
            }
            for(Assignment_Groups__c ag:trigger.new){
                if(ContainedIds.contains(ag.User__c)){
                    ag.User__c.addError('There exists an assignment group member with the same user');
                }
            }  
            }
        //Updated trigger to include a class to be called for both OOR and NMR    
        if(UpdatedList.size()>0){
            NMROORAsgroupmemberAlign.alignGrpMember(UpdatedIds,AssignGrpList,Trigger.ISINSERT,Trigger.ISUPDATE,Trigger.OldMap,UpdatedList);
        }                      
       
}